import { createSlice } from "@reduxjs/toolkit";

const counterSlice = createSlice({
  name: "counter",
  initialState: {
    value: 0,
  },
  reducers: {
    plus: (state, action) => {
      // Redux Toolkit allows us to write "mutating" logic in reducers. It
      // doesn't actually mutate the state because it uses the Immer library,
      // which detects changes to a "draft state" and produces a brand new
      // immutable state based off those changes
      state.value += action.payload;
    },
    minus: (state, action) => {
      state.value -= action.payload;
    },
    plusIfOdd: (state, action) => {
      if (state.value % 2 === 1) state.value += action.payload;
    },
    plusAsync: (state, action) => {
      /*
      setTimeout(()=>{
        state.value += action.payload
      }, 2000)
      */
      state.value += action.payload;
    },
  },
});

// Action creators are generated for each case reducer function
export const {
  plus: action_plus,
  minus: action_minus,
  plusIfOdd: action_plusIfOdd,
  plusAsync: action_plusAsync,
} = counterSlice.actions;

export default counterSlice.reducer;
